import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { Message, MessageBox } from 'element-ui'

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      console.log('派发Login的userInfo', userInfo);
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        console.log(username, userInfo.password);
        login(username, userInfo.password, 'admin').then(response => {
          if (response.isSuccee) {
            const data = response.data
            // const tokenStr = data.tokenHead+data.token
            setToken(data.token)
            commit('SET_TOKEN', data.token)
            // 存储为已登录
            sessionStorage.setItem('islogin', true)
            resolve()
          } else {
            console.log(response);
            Message.error(response.msg)
            reject()
          }
        }).catch(error => {
          console.log(error);
          sessionStorage.setItem('islogin', false)

          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {

        getInfo().then(response => {
          const data = response.data
          commit('SET_ROLES', ["超级管理员"])
          commit('SET_NAME', data.username)
          commit('SET_AVATAR', data.icon)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出 清除token
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resolve()
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
